package com.whpost.service.service.cwqf;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.cwqf.*;
import com.whpost.service.entity.cwqf.*;
import com.whpost.service.entity.cwqf.TCwqfKhjlKh;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TCwqfKhjlKhServices extends BaseServices<TCwqfKhjlKhMapper, TCwqfKhjlKh> {

    @Resource
    private TbCrmCustomerMapper tbCrmCustomerMapper;
    @Resource
    private HsCzyMapper hsCzyMapper;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="",sfjm="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("keyword")) {
                cxmc = jsonObject.getString("keyword");
            }

            if (StringUtils.isEmpty(sfjm)) sfjm = "1";
            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "30";

            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if (null==hsCzy){
                return new ResultInfo(500,"用户信息不存在！",null);
            }

            HsJg hsJg = getHsJgMapper().selectById(hsCzy.getSsjgLsh());

            Page<TCwqfKhjlKh> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TCwqfKhjlKh> tCwqfKhjlKhListInfo = new ListInfo<>();
            QueryWrapper<TCwqfKhjlKh> tCwqfKhjlKhQueryWrapper = new QueryWrapper<>();
            if (!StringUtils.isEmpty(cxmc)) {
                // 直接拼接变量值到SQL中（Oracle用||拼接字符串）
                tCwqfKhjlKhQueryWrapper.inSql(
                        "party_code",
                        "select party_code from TB_CRM_CUSTOMER " +
                                "where party_name like '%' || '" + cxmc + "' || '%' "
                );
            }

            tCwqfKhjlKhQueryWrapper.eq("czy_code",hsCzy.getCode());

            IPage<TCwqfKhjlKh> tQfkbBkIPage = getBaseMapper().getTCwqfKhjlKhPage(page,tCwqfKhjlKhQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(tQfkbBkIPage.getTotal());
            pageInfo.setCurPage(tQfkbBkIPage.getCurrent());
            pageInfo.setPageSize(tQfkbBkIPage.getSize());
            pageInfo.setPageTotal(tQfkbBkIPage.getPages());

            tCwqfKhjlKhListInfo.setPageInfo(pageInfo);
            tCwqfKhjlKhListInfo.setListInfo(tQfkbBkIPage.getRecords());
            tCwqfKhjlKhListInfo.setUserId(loginId);//登录人员id，可以不设置也行

            //加密返回给前端
            if ("1".equals(sfjm)){
                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",tCwqfKhjlKhListInfo);
                return backRtn(resultInfo,loginId);
            }else{
                //非加密,返回给其它方法使用
                return new ResultInfo(0, "成功返回！",tCwqfKhjlKhListInfo);
            }
        }
    }

    @Override
    public ResultInfo del(String loginId, Map<String, Object> map) {
        // 解析请求数据
        JSONObject jsonObject = getData(map, loginId);

        // 验证用户登录信息
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(500, "用户信息丢失！", null);
        }

        // 获取并验证删除相关参数
        JSONArray deleteIdsArray = jsonObject.getJSONArray("deleteIds");
        if (deleteIdsArray == null || deleteIdsArray.isEmpty()) {
            return new ResultInfo(500, "请选择要删除的客户！", null);
        }

        // 转换删除ID为列表
        List<Integer> deleteIds = new ArrayList<>();
        for (int i = 0; i < deleteIdsArray.size(); i++) {
            deleteIds.add(deleteIdsArray.getIntValue(i));
        }

        HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);
        if (null == hsCzy) {
            return new ResultInfo(500, "用户信息不存在！", null);
        }

        try {
            // 执行删除操作 - 根据实际表结构调整
            // 这里假设删除的是TCwqfKhjlKh表中的记录
            QueryWrapper<TCwqfKhjlKh> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.in("id", deleteIds)  // 使用前端传递的deleteIds
                    .eq("czy_code", hsCzy.getCode());  // 确保只能删除当前操作员的数据

            int deleteCount = getBaseMapper().delete(deleteWrapper);

            if (deleteCount > 0) {
                // 构建返回结果（保持与查询接口一致的加密逻辑）
                String sfjm = jsonObject.containsKey("sfjm") ? jsonObject.getString("sfjm") : "1";
                ResultInfo resultInfo = new ResultInfo(200, "成功删除" + deleteCount + "条记录！", null);

                // 根据加密标识决定返回方式
                if ("1".equals(sfjm)) {
                    return backRtn(resultInfo, loginId);
                } else {
                    return resultInfo;
                }
            } else {
                return new ResultInfo(500, "删除失败，未找到匹配的记录或没有删除权限！", null);
            }
        } catch (Exception e) {
            // 异常处理
            log.error("删除客户信息异常", e);
            return new ResultInfo(500, "删除失败：" + e.getMessage(), null);
        }
    }

    public ResultInfo delCode(String loginId, Map<String, Object> map) {
        // 解析请求数据
        JSONObject jsonObject = getData(map, loginId);

        // 验证用户登录信息
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(500, "用户信息丢失！", null);
        }

        // 获取并验证删除相关参数
        String khCode = jsonObject.getString("khCode");
        if (StringUtils.isEmpty(khCode)) {
            return new ResultInfo(500, "请选择要删除的客户！", null);
        }


        HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);
        if (null == hsCzy) {
            return new ResultInfo(500, "用户信息不存在！", null);
        }

        try {
            // 执行删除操作 - 根据实际表结构调整
            // 这里假设删除的是TCwqfKhjlKh表中的记录
            QueryWrapper<TCwqfKhjlKh> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("party_code", khCode)  // 使用前端传递的deleteIds
                    .eq("czy_code", hsCzy.getCode());  // 确保只能删除当前操作员的数据

            int deleteCount = getBaseMapper().delete(deleteWrapper);

            if (deleteCount > 0) {
                // 构建返回结果（保持与查询接口一致的加密逻辑）
                String sfjm = jsonObject.containsKey("sfjm") ? jsonObject.getString("sfjm") : "1";
                ResultInfo resultInfo = new ResultInfo(200, "成功删除" + deleteCount + "条记录！", null);

                // 根据加密标识决定返回方式
                if ("1".equals(sfjm)) {
                    return backRtn(resultInfo, loginId);
                } else {
                    return resultInfo;
                }
            } else {
                return new ResultInfo(500, "删除失败，未找到匹配的记录或没有删除权限！", null);
            }
        } catch (Exception e) {
            // 异常处理
            log.error("删除客户信息异常", e);
            return new ResultInfo(500, "删除失败：" + e.getMessage(), null);
        }
    }

    /**
     * 未认领客户列表
     * @param loginId
     * @param map
     * @return
     */
    public ResultInfo queryNo(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="",sfjm="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("keyword")) {
                cxmc = jsonObject.getString("keyword");
            }

            if (StringUtils.isEmpty(sfjm)) sfjm = "1";
            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "30";

            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if (null==hsCzy){
                return new ResultInfo(500,"用户信息不存在！",null);
            }

            HsJg hsJg = getHsJgMapper().selectById(hsCzy.getSsjgLsh());

            Page<TbCrmCustomer> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TbCrmCustomer> tbCrmCustomerListInfo = new ListInfo<>();
            QueryWrapper<TbCrmCustomer> tbCrmCustomerQueryWrapper = new QueryWrapper<>();
            if (!StringUtils.isEmpty(cxmc)) {
                // 直接拼接变量值到SQL中（Oracle用||拼接字符串）
                tbCrmCustomerQueryWrapper.like("party_name",cxmc);
            }

            tbCrmCustomerQueryWrapper.eq("1","1");

            IPage<TbCrmCustomer> tbCrmCustomerIPage = tbCrmCustomerMapper.selectCustomers(page,hsJg.getCode(),hsCzy.getCode(),tbCrmCustomerQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(tbCrmCustomerIPage.getTotal());
            pageInfo.setCurPage(tbCrmCustomerIPage.getCurrent());
            pageInfo.setPageSize(tbCrmCustomerIPage.getSize());
            pageInfo.setPageTotal(tbCrmCustomerIPage.getPages());

            tbCrmCustomerListInfo.setPageInfo(pageInfo);
            tbCrmCustomerListInfo.setListInfo(tbCrmCustomerIPage.getRecords());
            tbCrmCustomerListInfo.setUserId(loginId);//登录人员id，可以不设置也行

            //加密返回给前端
            if ("1".equals(sfjm)){
                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",tbCrmCustomerListInfo);
                return backRtn(resultInfo,loginId);
            }else{
                //非加密,返回给其它方法使用
                return new ResultInfo(0, "成功返回！",tbCrmCustomerListInfo);
            }
        }
    }

    @Override
    public ResultInfo save(String loginId, Map<String, Object> map) {
        // 解析请求数据
        JSONObject jsonObject = getData(map, loginId);

        // 验证用户登录信息
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(500, "用户信息丢失！", null);
        }

        // 获取并验证删除相关参数
        JSONArray deleteIdsArray = jsonObject.getJSONArray("deleteIds");
        if (deleteIdsArray == null || deleteIdsArray.isEmpty()) {
            return new ResultInfo(500, "请选择要认领的客户！", null);
        }

        // 转换删除ID为列表
        List<String> deleteIds = new ArrayList<>();
        for (int i = 0; i < deleteIdsArray.size(); i++) {
            deleteIds.add(deleteIdsArray.get(i).toString());
        }

        HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);
        if (null == hsCzy) {
            return new ResultInfo(500, "用户信息不存在！", null);
        }

        try {
            for (int k=0;k<deleteIds.size();k++){
                //先看有没有
                Long sl = getBaseMapper().selectCount(new QueryWrapper<TCwqfKhjlKh>().eq("czy_code",hsCzy.getCode()).eq("party_code",deleteIds.get(k)));
                if (sl==0){
                    TCwqfKhjlKh tCwqfKhjlKh = new TCwqfKhjlKh();
                    tCwqfKhjlKh.setCzyCode(hsCzy.getCode());
                    tCwqfKhjlKh.setCzyName(hsCzy.getName());
                    tCwqfKhjlKh.setPartyCode(deleteIds.get(k));
                    getBaseMapper().insert(tCwqfKhjlKh);
                }
            }

            // 构建返回结果（保持与查询接口一致的加密逻辑）
            String sfjm = jsonObject.containsKey("sfjm") ? jsonObject.getString("sfjm") : "1";
            ResultInfo resultInfo = new ResultInfo(200, "成功认领" + deleteIds.size() + "条记录！", null);

            // 根据加密标识决定返回方式
            if ("1".equals(sfjm)) {
                return backRtn(resultInfo, loginId);
            } else {
                return resultInfo;
            }
        } catch (Exception e) {
            // 异常处理
            log.error("认领客户信息异常", e);
            return new ResultInfo(500, "认领失败：" + e.getMessage(), null);
        }
    }

    public String test(){
        // Excel文件路径
        String filePath = "d:\\cwqf_zgxx.xls";


        List<Object> dataList = new ArrayList<>(); // 使用通用Object类型存储数据

        EasyExcel.read(filePath)
                .excelType(ExcelTypeEnum.XLS)
                // 使用Object作为泛型，兼容List和Map两种结构
                .registerReadListener(new ReadListener<Object>() {
                    @Override
                    public void invoke(Object rowData, com.alibaba.excel.context.AnalysisContext context) {
                        dataList.add(rowData);
                    }

                    @Override
                    public void doAfterAllAnalysed(com.alibaba.excel.context.AnalysisContext context) {
                        System.out.println("Excel文件内容如下：");
                        for (int i = 0; i < dataList.size(); i++) {
                            Object rowData = dataList.get(i);
                            String col1 = "";
                            String col2 = "";
                            String col3 = "";

                            // 处理List类型的行数据
                            if (rowData instanceof List) {
                                List<?> list = (List<?>) rowData;
                                col1 = list.size() > 0 ? getStringValue(list.get(0)) : "";
                                col2 = list.size() > 1 ? getStringValue(list.get(1)) : "";
                                col3 = list.size() > 2 ? getStringValue(list.get(2)) : "";
                            }
                            // 处理Map类型的行数据（LinkedHashMap是Map的实现类）
                            else if (rowData instanceof Map) {
                                Map<?, ?> map = (Map<?, ?>) rowData;
                                // 获取前三个键值对（或根据实际表头键名获取）
                                List<?> values = new ArrayList<>(map.values());
                                col1 = values.size() > 0 ? getStringValue(values.get(0)) : "";
                                col2 = values.size() > 1 ? getStringValue(values.get(1)) : "";
                                col3 = values.size() > 2 ? getStringValue(values.get(2)) : "";
                            }

                            String qjid=col1;
                            String zgxm = col2;
                            String sjh= col3;

                            System.out.println("准备添加：区局["+qjid+"]--职工["+zgxm+"]--手机号["+sjh+"]>>>开始");
                            HsCzy hsCzy = new HsCzy();

                            Long a = getMyDao().getNextSequenceValue("seq_hs_czy.nextval");

                            String str = "";

                            // 确保a不为null的情况下进行转换，避免空指针异常
                            if (a != null) {
                                // %08d 表示将数字格式化为8位，不足8位时前面补0
                                str = String.format("%08d", a);
                            }

                            hsCzy.setCode(str);
                            hsCzy.setName(zgxm);
                            hsCzy.setSsjgLsh(Long.parseLong(qjid));
                            try {
                                hsCzy.setTel(Url.encrypt(sjh));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                            String result = "";

                            // 校验字符串长度是否符合11位（手机号通常为11位）
                            if (sjh != null && sjh.length() == 11) {
                                // 截取前3位 + **** + 截取后4位
                                result = sjh.substring(0, 3) + "****" + sjh.substring(7);
                            } else {
                                // 不符合长度时可返回原字符串或做其他处理
                                result = "";
                            }

                            hsCzy.setSjwh(result);
                            hsCzy.setGljg(qjid);

                            hsCzyMapper.insert(hsCzy);

                            System.out.println("准备添加：区局["+qjid+"]--职工["+zgxm+"]--手机号["+sjh+"]>>>结束，增加成功");

                        }
                    }

                    @Override
                    public boolean hasNext(com.alibaba.excel.context.AnalysisContext context) {
                        return true;
                    }

                    // 辅助方法：将对象转为字符串
                    private String getStringValue(Object obj) {
                        return obj != null ? obj.toString() : "";
                    }
                })
                .sheet()
                .doRead();

        return "suc";
    }

    public String test1(){
        // Excel文件路径
        String filePath = "d:\\khgl.xls";


        List<Object> dataList = new ArrayList<>(); // 使用通用Object类型存储数据

        EasyExcel.read(filePath)
                .excelType(ExcelTypeEnum.XLS)
                // 使用Object作为泛型，兼容List和Map两种结构
                .registerReadListener(new ReadListener<Object>() {
                    @Override
                    public void invoke(Object rowData, com.alibaba.excel.context.AnalysisContext context) {
                        dataList.add(rowData);
                    }

                    @Override
                    public void doAfterAllAnalysed(com.alibaba.excel.context.AnalysisContext context) {
                        System.out.println("Excel文件内容如下：");
                        for (int i = 0; i < dataList.size(); i++) {
                            Object rowData = dataList.get(i);
                            String col1 = "";
                            String col2 = "";

                            // 处理List类型的行数据
                            if (rowData instanceof List) {
                                List<?> list = (List<?>) rowData;
                                col1 = list.size() > 0 ? getStringValue(list.get(0)) : "";
                                col2 = list.size() > 1 ? getStringValue(list.get(1)) : "";
                            }
                            // 处理Map类型的行数据（LinkedHashMap是Map的实现类）
                            else if (rowData instanceof Map) {
                                Map<?, ?> map = (Map<?, ?>) rowData;
                                // 获取前三个键值对（或根据实际表头键名获取）
                                List<?> values = new ArrayList<>(map.values());
                                col1 = values.size() > 0 ? getStringValue(values.get(0)) : "";
                                col2 = values.size() > 1 ? getStringValue(values.get(1)) : "";
                            }

                            String kh=col1;
                            String sjh = col2;

                            TCwqfKhjlKh tCwqfKhjlKh = new TCwqfKhjlKh();

                            HsCzy hsCzy = new HsCzy();
                            try {
                                hsCzy = hsCzyMapper.getHsCzyByTel(Url.encrypt(sjh));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }


                            tCwqfKhjlKh.setCzyCode(hsCzy.getCode());
                            tCwqfKhjlKh.setCzyName(hsCzy.getName());
                            tCwqfKhjlKh.setPartyCode(kh);

                            getBaseMapper().insert(tCwqfKhjlKh);




                        }
                    }

                    @Override
                    public boolean hasNext(com.alibaba.excel.context.AnalysisContext context) {
                        return true;
                    }

                    // 辅助方法：将对象转为字符串
                    private String getStringValue(Object obj) {
                        return obj != null ? obj.toString() : "";
                    }
                })
                .sheet()
                .doRead();

        return "suc";
    }

}
